<template>
  <div>
    <reply :receive-user-id="moduleAuthorId" @replied="replied" />
    <div class="comment-list">
      <comment-item
        v-for="comment in comments"
        :key="comment.id"
        :comment="comment"
        :module="module"
        :module-id="moduleId"
        class="list-item"
      />
    </div>
    <pagination
      v-if="pagination"
      :current-page="page.currentPage"
      :page-count="page.pageCount"
    />
    <load-more v-else :list="comments" :loading="loading" :next-page="nextPage" :auto-hide="true" />
  </div>
</template>

<script>
import { mapActions } from 'vuex';
import LoadMore from '@/components/load-more';
import { formatComments } from '@/components/shared/comments/format';
import CommentItem from './components/comment-item';
import Reply from './components/reply';

export default {
  name: 'comments-plain', // 参考bilibili的评论区（非富文本）
  components: { LoadMore, CommentItem, Reply },
  props: {
    module: { // 该评论区所在位置类型，直接匹配后端
      type: String,
      required: true,
    },
    moduleId: { // 该评论区所在位置id
      type: Number,
      required: true,
    },
    moduleAuthorId: { // 评论区所在位置，是谁创的
      type: Number,
      required: true,
    },
    pagination: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      loading: false,
      comments: [],
      nextPage: null,
      page: {},
    };
  },
  computed: {
    loadCommentsParams() {
      return {
        placement: this.module,
        placementId: this.moduleId,
        page: this.$route.query.page,
        order: 'asc',
      };
    },
  },
  created() {
    this.updateCurModule({ type: this.module, id: this.moduleId });
    this.loadComments();
  },
  destroyed() {
    this.updateCurModule();
  },
  methods: {
    ...mapActions('comments', { updateCurModule: 'updateCurrentModule' }),
    // 加载评论列表
    loadComments(page = 1) {
      this.loading = true;
      const params = this.pagination
        ? this.loadCommentsParams
        : {
          placement: this.module,
          placementId: this.moduleId,
          page,
          order: 'desc',
        };
      this.$api.comments.index(params).then((res) => {
        const results = formatComments(res.data);
        if (this.pagination) this.comments = results;
        else this.comments = this.comments.concat(results);
        this.nextPage = res.kaminari.next_page;
        this.page.currentPage = res.kaminari.current_page;
        this.page.pageCount = res.kaminari.total_pages;
      }).catch(() => {})
        .then(() => { this.loading = false; });
    },
    // 回复了
    replied(comment) { this.comments.unshift(comment); },
  },
  watch: {
    loadCommentsParams() {
      if (this.pagination) this.loadComments();
    },
  },
};
</script>

<style lang="scss">
.comment-list .list-item .con {
  border-top: 1px solid #e5e5e5;
}
</style>
